package com.gavin.utils;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Hashtable;

/**
 * ------------------------------
 * 公共工具
 * ------------------------------
 * @author wdm（l311576@sina.com）  @date 2018年7月26日
 * @version 1.0
 */
public class Utility {

	private static Hashtable<String, Charset> htCharset = new Hashtable<String, Charset>();
	public final static Charset UTF_8 = Charset.forName("utf-8");

	public Utility() {}

	public final static void sleep(int nMilliSecond) {
		try {
			Thread.sleep(nMilliSecond);
		} catch (Exception e) {
		}
	}
	
	
	public final static Charset getCharset(String strCharset) {
		strCharset = strCharset.toLowerCase();
		Charset cs = htCharset.get(strCharset);
		if (cs == null) {
			cs = Charset.forName(strCharset);
			htCharset.put(strCharset, cs);
		}
		return cs;
	}

	
	/**
	 * 使用分隔符将字符串分隔
	 * @param strSource
	 * @param chSeperator
	 * @return
	 */
	public static String[] splitString(String strSource, char chSeperator) {
		ArrayList<String> alOutput = new ArrayList<String>();
		StringBuilder strbString = new StringBuilder();
		for (int i = 0; i < strSource.length(); i++) {
			char chChar = strSource.charAt(i);
			if (chChar == chSeperator) {
				alOutput.add(strbString.toString());
				strbString = new StringBuilder();
			} else {
				strbString.append(chChar);
			}
		}
		alOutput.add(strbString.toString());
		String[] strsOutput = new String[alOutput.size()];
		for (int i = 0; i < alOutput.size(); i++) {
			strsOutput[i] = (String) alOutput.get(i);
		}
		return strsOutput;
	}

	// --------------------------------------------参数操作-------------------------------------------------
	/**
	 * 根据Key获取系统环境变量的值
	 * 
	 * @param strKey
	 *            Key格式为{key}，如果格式非法或环境变量不存在则以Key当作值
	 * @return 环境变量的值或者key
	 */
	final public static String getEnvValue(String strKey) {
		String strOldKey = strKey;

		int nLength = strKey.length();
		if (nLength <= 2) {
			return strOldKey;
		}
		if (strKey.charAt(0) != '{' || strKey.charAt(nLength - 1) != '}') {
			return strOldKey;
		}

		// 环境变量
		strKey = strKey.substring(1, nLength - 1);

		String strValue = System.getenv().get(strKey);
		if (strValue != null) {
			return strValue;
		}

		strValue = System.getenv().get(strKey.toUpperCase());
		if (strValue != null) {
			return strValue;
		}

		strValue = System.getenv().get(strKey.toLowerCase());
		if (strValue != null) {
			return strValue;
		}

		throw new RuntimeException("EnvValue not found: " + strOldKey);
	}

	public static String findAndGetStringAhead(String strSource, int nFromIndex, String strSearchFor) {
		int nIndex = strSource.indexOf(strSearchFor, nFromIndex);
		if (nIndex < 0) {
			return null;
		}
		return strSource.substring(nFromIndex, nIndex);
	}

}
